<template>
  <div class='box-wrap-total'>
    <section class='box-operation'>
      <div class="box-search">         
        <div class='form-group-enquire'>
          <el-select v-model="searchData.account_id" placeholder="充值账户" clearable filterable>
            <el-option :value= row.id v-for="row in rolelist" :label="'('+ row.id+')'+row.name" :key= row.id ><span style="float:left;color:#FF0000">({{row.id}})&nbsp;</span>{{row.name}}</el-option>
          </el-select>
        </div>    
        <div class='form-group-enquire'>
          <el-select v-model="searchData.creator" placeholder="充值人员" clearable filterable>
            <el-option :value= row.id v-for="row in rolelist2" :label="row.name" :key= row.id >{{row.name}}</el-option>
          </el-select>
        </div> 
        <div class='form-group-enquire'>
          <DatePicker type="daterange" placeholder="日期" style="width: 190px" :editable=false  v-model="searchDate" @on-change="changeDate" @on-clear="initDate"></DatePicker>
        </div>              
        <div class='form-group-img' @click='onSearchGetList()'><img src="../../assets/images/peach-svg/Frame 23.svg"></div>
        <div class='form-group-addimg' @click='editInfo({},1)'><img src="../../assets/images/peach-svg/addcz.svg"></div>
        <div class='form-group-addimg6' @click='editInfo({},2)'><img src="../../assets/images/peach-svg/tuikuang.svg"></div>
        <div class='form-group-addimg2' @click='downloadFile(1,{})'><img src="../../assets/images/peach-svg/export.svg"></div>
      </div>
    </section>
    <LibVxeTable class="staticData" :stripe="stripe" :show-footer="showFooter" :footer-method="footerMethodFunc" border="none" :tableColumns="tableColumns" :tableData="list" :slotHeader="slotHeader" :PageObj="{total:totalCnt,currentPage:searchData.page_index,pageSize:searchData.page_size}"  @onPageChange="onChangePageSize" @onSelectChange="onCheckChange" resizable></LibVxeTable>
  </div>
</template>
<script>
import { mapGetters } from "vuex";
import utils from "../../commons/utils";
import {commonMixin} from "../../components/ViewInitMixin" //每一个文件都要包含这个
import {TimePicker} from "iview"
import SearchUser from "../searchUser"
import Request from "../../commons/Request"
import {ACDN} from '../../commons/staticName'
import store from "@/commons/store"
import bus from "../../commons/EventBus";

export default {
  name: "addUserDetailView",  //!!这块一定要注意，每一个文件都根据资源path来命名
  components:{TimePicker,SearchUser},
  mixins:[commonMixin],
  data() {
    const validateAccount = (rule, value, callback) =>{
      if(value == "" || value == undefined){
        callback(new Error("账户必须选择"));
      }else {
        callback();
      }
    };
    const validaterecharge = (rule, value, callback) =>{
      if(value < 0.0001 && (value!=""||value!=0)){
        callback(new Error("充值积分不能小于0.0001"));
      }else {
        callback();
      }
    };
    const validaterecharge1 = (rule, value, callback) =>{
      if(value < 0.0001 && (value!=""||value!=0)){
        callback(new Error("赠送积分不能小于0.0001"));
      }else {
        callback();
      }
    };
    const validaterefund_p = (rule, value, callback) =>{
      if(value == "" || value == undefined){
        callback(new Error("退款积分不能为空"));
      }else if(value < 0.0001 ){
        callback(new Error("退款积分不能小于0.0001"));
      }else {
        callback();
      }
    };
    return {
      stripe:false,       
      statuslist: [{id:1,name:'启用'},{id:2,name:'禁用'}],
      modal:false,
      searchDate:"",
      searchTime:[utils.dateFormat(0,"HH")+"00",utils.dateFormat(0,"HH")+"00"],
      searchDate:"",
      searchData:{
        account_id:"",
        start:"",
        end:"",
        page_index:1,
        page_size:30,
      },
      list:[],
      totalCnt:0,
      bonus_pointsCnt: 0,
      recharge_pointsCnt: 0,
      refund_pointsCnt: 0,
      residual_pointsCnt: 0,
      total_pointsCnt: 0,
      info:{},
      selectRows:[],
      formPopIndex:0,
      footerMethod:{},    
      rolelistObj:{},  
      roleslistObj:{},  
      rolelist:[],
      rolelist2:[],
      rolelist3:[],
      tableColumns:[
        { 
        field: "Id",
        type:"checkbox",
        align: "center",
        width:50,
        },
        {
          title: "序号",
          field: "seq",
          align: 'center',
        },
        {
          title: "充值账户",
          field: "account_name",
          align: 'center',
          // slots:{
          //   default:({row},h)=>{
          //       if (row.account_id==''||row.account_id==undefined) {
          //           return [h("span","--")]
          //       }else{
          //           return this.rolelistObj[row.account_id]
          //       }
          //   }
          // }
        },
        {
          title: "剩余积分",
          field: "residual_points",
          align: 'center',
          slots:{
            default:({row},h)=>{
                if (row.residual_points==''||row.residual_points==undefined) {
                    return [h("span","--")]
                }else{
                    return (row.residual_points/10000)
                }
            }       
          }   
        },     
        {
          title: "充值积分",
          field: "recharge_points",
          align: 'center',
          slots:{
            default:({row},h)=>{
                if (row.recharge_points==''||row.recharge_points==undefined) {
                    return [h("span","--")]
                }else{
                    return (row.recharge_points/10000)
                }
            }     
          }     
        },     
        {
          title: "赠送积分",
          field: "bonus_points",
          align: 'center',
          slots:{
            default:({row},h)=>{
                if (row.bonus_points==''||row.bonus_points==undefined) {
                    return [h("span","--")]
                }else{
                    return (row.bonus_points/10000)
                }
            }         
            } 
        },     
        {
          title: "退款积分",
          field: "refund_points",
          align: 'center',
          slots:{
            default:({row},h)=>{
                if (row.refund_points==''||row.refund_points==undefined) {
                    return [h("span","--")]
                }else{
                    return (row.refund_points/10000)
                }
            }       
            }   
        },     
        {
          title: "积分总额",
          field: "total_points",
          align: 'center',
          slots:{
            default:({row},h)=>{
                if (row.total_points==''||row.total_points==undefined) {
                    return [h("span","--")]
                }else{
                    return row.total_points/10000
                }
            }     
            }     
        },        
        {
          title: "代理账号",
          field: "leader_account",
          align: 'center',
          slots:{
            default:({row},h)=>{
                if (row.leader_account==''||row.leader_account==undefined) {
                    return [h("span","--")]
                }else{
                    return row.leader_account
                }
            }          
            }
        },  
         {
          title: "充值时间",
          field: "create_at",
          align: 'center',
          slots:{
            default:({row},h) =>{
              if(row.create_at==0){
                return [h("div",'-')]
              }else
              return [h("div",utils.dateFormat(row.create_at,"yyyy-MM-dd HH:mm:ss"))]
            }
          }
        },
        {
          title: "充值人员",
          field: "creator_name",
          align: 'center',
          slots:{
            default:({row},h)=>{
                if (row.creator_name==''||row.creator_name==undefined) {
                    return [h("span","--")]
                }else{
                    return row.creator_name
                }
            }     
            }     
        }      
      ],
      format: {  
        account_id:{
          labelName: "充值账户",
          labelType: "select",   
          labelValue:"",      
          placeholder:"请输入充值账户",
          labelChange:"account_id",
        },
        nameuser:{
          labelName: "账户角色",
          labelType: "text", 
          placeholder:""
        },
        recharge_points:{
          labelName: "充值积分",
          labelType: "Number",      
          placeholder:"请输入充值积分"
        },
        bonus_points:{
          labelName: "赠送积分",
          labelType: "Number",     
          placeholder:"请输入赠送积分",
          labelMessage:"提示：1积分=1元"
        },   

        namestore:{
          labelName: "代理商",
          labelType: "select",    
          labelValue:"",   
          placeholder:"请输入代理商"
        },
        namecount2:{
          labelName: "退款账户",
          labelType: "select",    
          labelValue:"",   
          placeholder:"请输入退款账户"
        },
        refund_points:{
          labelName: "退款积分",
          labelType: "Number",     
          placeholder:"请输入退款积分",
        },    
        refund_ty:{
          labelName: "退款类型",
          labelType: "radio",     
          labelValue:[{key:1,value:"充值"},{key:2,value:"赠送"}]
        }           
      },     
      ruleValidate: {
        account_id: [{ required: true,validator:validateAccount, trigger: "blur" }],
        recharge_points: [{ validator: validaterecharge}],
        bonus_points: [{ validator: validaterecharge1}],
        refund_points: [{ required: true,validator:validaterefund_p, trigger: "blur" }],
      },      
      dateOptions:{
        disabledDate(date){
          return date && date.valueOf() > Date.now();
        },

      },
    };
  },
  computed: {
            ...mapGetters(["UserInfo"]),         
        },
  methods: {
    async initView(isMounted){
      if(isMounted){
        await this.getList();
        await this.initSearchData();
      }

    },
    async initSearchData() {
      //用户管理接口
      let res3 = await Request.post("customer/user", "query_list");
      let res = await Request.post("customer/user", "query_list",{role_id:3});
      let res2 = await Request.post("customer/user", "query_list",{role_id:this.UserInfo.role_id});
      this.rolelistObj = {}
      this.roleslistObj = {}
      this.rolelist=[]
      this.rolelist2=[]
      this.rolelist3=[]
      this.format.account_id.labelValue=[]
      if(res.code==0 && res.data != null){
        res.data.list.forEach((item) => {
          this.$set(this.rolelistObj,item.id,item.account)
          this.$set(this.roleslistObj,item.id,item.role_name)
          this.rolelist.push({id:item.id,name:item.account});
        })  
      }
      if(res2.code==0 && res2.data != null){
        res2.data.list.forEach((item) => {
          this.rolelist2.push({id:item.id,name:item.account});
        })  
      }
      if(res3.code==0 && res3.data != null){
        res3.data.list.forEach((item) => {
          this.rolelist3.push({id:item.id,name:item.account});
        })  
      }
    },
    onSearchGetList(){
      this.searchData.page_index =1;
      this.getList();
    },
    async getList(){
      utils.showLoading()
      let res = await this.RequestPost("query_list",this.searchData); 
      if(res.code==0 && res.data != null){
        this.list = [];
        if(res.data.list!=null)
        this.list = res.data.list;
        this.totalCnt = res.data.total
        this.bonus_pointsCnt = (res.data.all.bonus_points/10000)
        this.recharge_pointsCnt = (res.data.all.recharge_points/10000)
        this.refund_pointsCnt = (res.data.all.refund_points/10000)
        this.residual_pointsCnt = (res.data.all.residual_points/10000)
        this.total_pointsCnt = (res.data.all.total_points/10000)
      }
      await utils.sleepMs(500)
      utils.hideLoading();
    },    
    //添加 编辑用户
    async editInfo(row,type) {
      this.handleType=type;
      let title = "";
      let info = {};
      if(this.handleType==1){
        title = "充值";
        this.format.account_id.labelName="充值账户"
        this.format.nameuser.labelDisabled = true
        this.format.account_id.labelValue=this.rolelist
        info = {
          account_id:"",    
          nameuser:"",
          recharge_points: "",     
          bonus_points:"",
          type:1,
          req_id:new Date().getTime()
        };
        this.onSelectChange("account_id",info.account_id);
      }else{
        title = "退款";
        this.format.account_id.labelName="退款账户"
        this.format.nameuser.labelDisabled = true
        this.format.account_id.labelValue=this.rolelist3
        info = {  
          account_id:row.account_id,   
          nameuser:"", 
          refund_ty:1,
          refund_points:row.refund_points,
          type:2,
          req_id:new Date().getTime()
        };
        this.onSelectChange("account_id",info.account_id);
      }
      this.formPopIndex=await utils.showFormPage(
        { title: title,message:this.UserInfo.role=="代理商"?("充值积分："+this.UserInfo.message+"，赠送积分："+this.UserInfo.bonus_points):"",el:this.$parent.$el,width:700,cancelBtnStatus:0},
        info,
        this.format,
        this.ruleValidate,
        this.updateInfo,
        this.onSelectChange,
      );
    },     
    async updateInfo(info) {
      utils.showLoading()
      let code = -1;
      let actionName = '';
      let tipText = '';
      let postData = utils.cloneObj(info);
      if (this.handleType==1) {
        actionName = 'add_item';
        tipText = '充值成功！';  
        postData["recharge_points"]= Math.round(info.recharge_points*10000)
        postData["bonus_points"]= Math.round(info.bonus_points*10000)
      }else if(this.handleType==2){
        actionName = 'add_item';
        tipText = '退款成功！';       
        postData["refund_points"]= Math.round(info.refund_points*10000)
      }else if(this.handleType==-1){
        actionName = 'del_item';
        tipText = '删除成功！';
        postData = {"id":postData.Id};
      }else if(this.handleType==3){
        actionName = 'enable_item';
        tipText = '启用成功！';
        postData = {"id":postData.id};
      }else if(this.handleType==4){
        actionName = 'disable_item';
        tipText = '禁用成功！！';
        postData = {"id":postData.id};
      }
      let res = await this.RequestPost(actionName, postData);
      code = res.code;
      console.log(res,"resres")
      if (code == 0) {
        utils.hideFormPage(this.formPopIndex);
        await utils.sleepMs(1000);
        this.onSearchGetList();
        utils.showTip(tipText);
      }else{
        utils.shadowModel({"icon":require('../../assets/images/peach-svg/hongtan.svg'),
         "modalContent":res.data,
         "title":"提示"});
      }
      utils.hideLoading();
    },       
    onCheckChange(rows){
        this.selectRows = [];
        this.selectRows = rows;
    },
    //删除
    sureDel(item,type) {
       this.handleType = -1;
        utils.showSureModal({
          "title":"删除提示",            
          "icon":require('../../assets/images/peach-svg/Frame 427318277 (1).svg'),
          "modalContent":"确认删除 "+item.name,"callBackArgs":{"Id":item.id}},(res)=>{
        let code = res.code;
        if(code==0){
          let data = res.data;
          this.updateInfo(data);
        }
      });
      this.getList()
    }, 
    //导出
    async downloadFile() {
      // utils.showLoading("正在生成中")
      let new_ids=""
      let new_seqs=""
      if((this.selectRows.checked==true && this.selectRows.records.length!= 0)||(this.selectRows.checked==false && this.selectRows.records.length!= 0)){
        //导出值用id|id形式拼接
        this.selectRows.records.forEach(item => {
          new_ids+='|'+item.id
          new_seqs+="|"+item.seq
        });
        if(new_ids!=''){
          new_ids=new_ids.substring(1)
        }
        if(new_seqs!=''){
          new_seqs=new_seqs.substring(1)
        }
        let res = await this.RequestPost("export_list",{"ids":new_ids,"seqs":new_seqs});
        if(res.code==0){
          utils.hideLoading()
            await utils.sleepMs(500);
            // let blob=new Blob([res.data],{type:'app/xml'})
            // utils.showTip("导出成功，在IM中查收");
            window.location.href = ACDN+res.data
        }else{
          utils.showSureModal({"icon":require('../../assets/images/peach-svg/hongtan.svg'),
         "modalContent":res.data,
         "title":"提示"});
        }
      }else{
         utils.showSureModal({"icon":require('../../assets/images/peach-svg/bluegth.svg'),
         "modalContent":"请选择一项",
         "title":"提示"});
      }
      
    },       
    onChangePageSize(page,pageSize){
      this.modal = true        
      this.searchData.page_index = page;
      this.searchData.page_size = pageSize;
      this.getList();
    },
    changeDate(val){
      let num = new Date(val)
      let time = num.getTime()/1000;
      // this.searchData.create_at = time
    },    
    onSelectChange(label,value,reset){
       //筛活跃数据来源判断显示
        if(label=="account_id"){
            this.format.nameuser.placeholder=this.roleslistObj[value]
        }
    },    
    slotHeader(h) {
      return [h("div",{class:{"allCount":true},"style":{"margin-left":"10px"}})]
    },
    //总计
    footerMethodFunc({ columns, data }){
      return [columns.map((item,index) => {
          if(index ==0){
            return '总计'
          }else if(['剩余积分'].includes(item.title)){
            return this.residual_pointsCnt
          }else if(['充值积分'].includes(item.title)){
            return this.recharge_pointsCnt
          }else if(['赠送积分'].includes(item.title)){
            return this.bonus_pointsCnt
          }else if(['退款积分'].includes(item.title)){
            return this.refund_pointsCnt
          }else if(['积分总额'].includes(item.title)){
            return this.total_pointsCnt
          }
          return null
        })
      ]
    },    
    changeDate(){
      this.searchData.start = Date.parse(this.searchDate[0])/1000;
      this.searchData.end = Date.parse(this.searchDate[1])/1000+86400;
      this.onSearchGetList();
    },
    initDate(){
      let nowDay = ""
      let beginDay = nowDay;
      let endDay = nowDay;
      this.searchDate = [new Date(beginDay),new Date(endDay)];
      this.changeDate();
    },
    unitprice(data){
      let unit_price = 0
      data.forEach(item =>{
        unit_price+=item.unit_price
      })
      return unit_price
    },
    showFooter(){
     if(this.footerMethod){
         return true;
     }else{
         return false;
     }      
    }    
  },
  mounted() {
    bus.$on('update-recharge-account-list', this.initSearchData);// 更新充值账户列表
  },

  beforeDestroy() {
    bus.$off('update-recharge-account-list');
  },
};
</script>  